/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ipccenter.toster.ejb;

import com.sun.xml.ws.api.tx.at.Transactional;
import edu.ipccenter.toster.Answer;
import edu.ipccenter.toster.Session;
import edu.ipccenter.toster.Suite;
import edu.ipccenter.toster.SuiteUtils;
import edu.ipccenter.toster.jpa.*;
import java.math.BigInteger;
import java.util.*;
import javax.ejb.EJB;
import javax.ejb.Stateful;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author 7
 */
@Stateful(name = "Session")
@Transactional
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class SessionBean implements Session {

    @EJB
    SuiteUtils suiteUtils;
    @PersistenceContext(unitName = "TosterPU")
    private EntityManager em;
    private JPASession session;
    private Set<Answer> answer = new HashSet();

    @Override
    public JPASession getSessionData() {
        return session;
    }

    @Override
    public void setSessionData(JPASession data) {
        if (data == null) {
            return;
        }
        this.session = data;

    }

    @Override
    public void setSuite(Suite suite) {
        if (session.getEnd_date() != null) {
            return;
        }
        if (session.getSuit_id() != null) {
            return;
        }
        session.setStart_date(new Date());
        session.setSuit_id(suite.getID());
        em.merge(session);
    }

    @Override
    public Suite getSuite() {
        if (session == null) {
            return null;
        }
        if (session.getSuit_id() == null) {
            return null;
        }
        return suiteUtils.findByID(session.getSuit_id());
    }

    @Override
    public Date getStartDate() {
        if (session == null) {
            return null;
        }
        return session.getStart_date();
    }

    @Override
    public Date getEndDate() {
        if (session == null) {
            return null;
        }
        return session.getEnd_date();
    }

    @Override
    public void closeSession() {
        if (session == null) {
            return;
        }
        if (session.getEnd_date() != null) {
            return;
        }
        if (session.getSuit_id() == null) {
            return;
        }
        Date end = new Date();
        session.setEnd_date(end);
        em.merge(session);

    }

    @Override
    public Set<Answer> getUserAnswers() {
        if (session == null) {
            return null;
        }
        answer = new HashSet();
        Query q = em.createQuery("select c from JPAUserTest c where c.session_id = :ses_id");
        q.setParameter("ses_id", session.getId());

        List<JPAUserTest> jusertest = q.getResultList();

        for (int i = 0; i < jusertest.size(); i++) {
            Answer ans = new Answer();
            ans.setID(jusertest.get(i).getTc_id());
            ans.setAnsNum(jusertest.get(i).getAnsNum());
            ans.setContent(jusertest.get(i).getAnsContent());

            answer.add(ans);
        }

        return answer;
    }

    @Override
    public void setAnswer(Answer answer) {
        if (session.getEnd_date() != null) {
            return;
        }
        JPAUserTest test = new JPAUserTest();

        test.setId(session.getId());
        test.setAnsNum(answer.getAnsNum());
        test.setTc_id(answer.getID());
        try {
            em.merge(test);

            this.answer.add(answer);
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }

    }

    @Override
    public BigInteger getSessionId() {
        return session.getId();
    }

    @Override
    public BigInteger getUserId() {
        if (session == null) {
            return null;
        }
        return session.getUser_id();
    }

    @Override
    public void checkResults() {
        if (session == null) {
            return;
        }

        if (session.getEnd_date() != null) {
            Set<Answer> userAns = getUserAnswers();
            if (userAns == null) {
                return;
            }

            List<Answer> testAnswers = new ArrayList<Answer>();

            Suite su = getSuite();
            if (su == null) {
                return;
            }
            Iterator iter;
            Iterator answ;

            JPATestSuite s = (JPATestSuite) su.getSuite();
            Set<JPATestCase> quest = s.getTestcase();

            iter = quest.iterator();
            while (iter.hasNext()) {
                JPATestCase tc = (JPATestCase) iter.next();

                answ = tc.getAnswers().iterator();
                while (answ.hasNext()) {

                    JPAAnswer a = (JPAAnswer) answ.next();
                    Answer ad = new Answer();
                    ad.setID(a.getTcId());
                    ad.setAnsNum(a.getAnsNum());
                    ad.setContent(ad.getContent());
                    if (a.getIscorrect() == 0) {
                        ad.setCorrectness(false);
                    } else {
                        ad.setCorrectness(true);
                    }
                    testAnswers.add(ad);
                }
            }

            //  System.out.println("UserAns:"+userAns);
            // System.out.println("RealAnsw:"+testAnswers);

            Iterator us;
            Iterator test = testAnswers.iterator();

            while (test.hasNext()) {
                Answer one = (Answer) test.next();

                if (one.isCorrect()) {
                    us = userAns.iterator();
                    while (us.hasNext()) {
                        Answer two = (Answer) us.next();
                        if (one.getID().equals(two.getID()) && one.getAnsNum().equals(two.getAnsNum())) {
                            //Answer Right
                            JPAUserTest mark = new JPAUserTest();

                            mark.setId(session.getId());
                            mark.setAnsNum(one.getAnsNum());
                            mark.setTc_id(one.getID());
                            mark.setMark(new Short("1"));

                            em.merge(mark);

                        }

                    }


                }
            }


        }
    }

    @Override
    public Short getResult() {
       
        if(session == null) return null;
        if(session.getEnd_date() == null) return null;
        
         Short result = null;
        
        Query q = em.createQuery("select c from JPAUserTest c where c.session_id = :id");
        q.setParameter("id", session.getId());
        
        List<JPAUserTest> results = q.getResultList();
        if(results  == null ) return null;
        
        int res = 0;
        Short one = new Short("1");
        for(int i = 0; i< results.size(); i++){
            JPAUserTest line = results.get(i);
            System.out.println(""+line.getMark());
            if(line.getMark()!=null && line.getMark().equals(one)) res++;
         
        }
        result = new Short(""+res);
        
        return result;
    }
}
